<template>
 <div>
<!--   表单-->
   <div v-if="username && !disabled" style="border: 1px solid #8cc5ff; border-radius: 10px">
     <div style="margin-top: 10px" />
     <h4 style="margin-left: 40px">发表评论</h4>
     <el-form :model="form" label-width="80px" ref="form" :rules="rules">
      <el-form-item label="评分" prop="score">
        <el-rate v-model="form.score" />
      </el-form-item>
       <el-form-item label="内容" prop="content">
         <el-input v-model="form.content" maxlength="75" show-word-limit type="textarea"/>
       </el-form-item>
       <el-form-item>
         <el-button type="primary" @click="submit">发送</el-button>
         <el-button @click="resetForm">重置</el-button>
       </el-form-item>
     </el-form>
   </div>
<!--   评论项-->
   <div class="items" v-if="comments.length">
     <div :key="i.id" v-for="i in currentPage" class="item">
       <comment-item
           :username="i.username"
           :score="i.score"
           :content="i.content" />
     </div>
     <template v-if="page !== 1 && this.lessItems !== 0">
       <div v-for="i in this.lessItems" :key="i">
        <div class="item placeholder" />
       </div>
     </template>
   </div>
   <div v-else>
     <el-empty description="还没有评论~" />
   </div>
<!--   分页-->
   <div>
     <el-pagination
         :total="this.comments.length"
         :page-size="10"
         hide-on-single-page
         :current-page.sync="page"
     />
   </div>
 </div>
</template>

<script>
import CommentItem from "@/components/comments/CommentItem";
import {mapState} from "vuex";
export default {
  name: "CommentPane",
  components: {CommentItem},
  data() {
    return {
      form: {
        score: 0,
        content: ""
      },
      rules: {
        score: [
          {min: 1, max: 5, type: "number", message: '您还没有评分！'},
        ]
      },
      page: 1
    }
  },
  methods: {
    resetForm() {
      this.$refs.form.resetFields();
    },
    submit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.$emit("submit", {content: this.form.content, score: this.form.score})
        }
      })
    }
  },
  props: {
    comments: {
      required: true,
      type: Array
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    currentPage() {
      return this.comments.slice(10 * (this.page - 1), 10 * this.page)
    },
    lessItems() {  // 对当前页面而言, 还有多少条目可以填满页面
      return 10 - this.currentPage.length
    },
    ...mapState({
      username: state => state.username
    })
  }
}
</script>

<style scoped>
.item:first-child {
  margin-top: 10px;
}
.item {
  border: 1px solid #8cc5ff;
  border-radius: 10px;
  padding: 10px;
  margin-bottom: 20px;
}

.placeholder {
  width: 1464px;
  height: 44px;
  border-style: none;
}
</style>